package com.wjm;

import com.wjm.until.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Data:2022年09月06日
 * Author:wjm
 * Content:   获得新增数据的自增主键值
 *
 *   2个步骤：
 *      1.在创建PreparedStatement对象的同时，传入第二个参数，指定该操作需要返回自增主键值
 *      PreparedStatement ps = connection.preparedStatement(sql, PreparedStatement.常量);
 *      其中，常量取值：
 *         RETURN_ GENERATED_KEYS ( = 1) 返回自增主键
 *         NO_GENERATED_KEYS ( = 2)
 *         CLOSE_CURRENT_RESULT ( = 1)
 *         KEEP_CURRENT_RESULT ( = 2)
 *         CLOSE_ALL_RESULTS ( = 3)
 *         EXECUTE_FAILED ( = -3)
 *         sucCESS_NO_INFO( = -2)
 *     2.通过PreparedStatement引用，调用getGeneratedKeys()方法，获取主键结果集。
 *
 */
public class JdbcAutoKeys {
    public static void main(String[] args) {
        try (Connection connection = JdbcUtil.getConnection();){
            //sql
            String sql = "insert into users value(null,?,?);";

            //创建语句对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);

            //赋值
            preparedStatement.setString(1,"陈");
            preparedStatement.setString(2,"123456");

            //执行
            preparedStatement.execute();

            //获取新增数据的自增主键
            ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
            while (generatedKeys.next()){
                System.out.println(generatedKeys.getInt(1));
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
